package cn.neusoft.service.impl;


import cn.neusoft.mapper.FoodMapper;
import cn.neusoft.pojo.Food;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.BusinessQuery;
import cn.neusoft.query.FoodQuery;
import cn.neusoft.service.IFoodService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;
import java.util.List;

/**
 * 这里调用dao层的封装
 * servlet调用服务层
 */
@Service
public class FoodService implements IFoodService {


	@Autowired
	private FoodMapper foodMapper;
	@Transactional
	public ResultBean add(Food food) throws Exception {
		if(food==null || StringUtils.isEmpty(food.getFoodName())) {
			return ResultBean.ERROR("请求参数为空");
		}
		int count= foodMapper.add(food);
		return count>0?ResultBean.SUCCESS(food.getFoodId()):ResultBean.ERROR("add is failed");
	}
	@Transactional
	public ResultBean update(Food food) throws Exception {
		if(food==null || StringUtils.isEmpty(food.getFoodName()) ||
		food.getFoodId()==null||
		food.getFoodId()==0) {
			return ResultBean.ERROR("请求参数为空");
		}
		int count= foodMapper.update(food);
		return count>0?ResultBean.SUCCESS():ResultBean.ERROR("update is failed");
	}
	@Transactional
	public ResultBean delete(Integer id) throws Exception {
		if(id==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		int count = foodMapper.delete(id);
		return count>0?ResultBean.SUCCESS():ResultBean.ERROR("delete is failed");
	}
	@Transactional(readOnly = true)
	public ResultBean getById(Integer id) throws Exception {
		if(id==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		Food food = foodMapper.getById(id);
		return food!=null?ResultBean.SUCCESS(food):ResultBean.ERROR("getById is failed");
	}
	@Transactional(readOnly = true)
	public ResultBean getAll() throws Exception {
		List<Food> list=foodMapper.getAll();
		return ResultBean.SUCCESS(list);
	}
	@Transactional(readOnly = true)
	public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
		PageBean<Food> pageBean=new PageBean<Food>();
		if(baseQuery==null) {
			baseQuery=new FoodQuery();
		}
		int count= foodMapper.getCount(baseQuery);
		pageBean.setTotalRows(count);

		List<Food> list=foodMapper.getByPage(baseQuery);
		pageBean.setData(list);
		return ResultBean.SUCCESS(pageBean);
	}
	@Transactional
	public ResultBean batchDel(List<Integer> ids) throws Exception {
		if(ids==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		for (Integer len : ids ) {
			int delete = foodMapper.delete(len);
			if(delete<0) {
				System.out.println("删除商家失败");
			}
		}
		return ResultBean.SUCCESS();
	}

	@Override
	public ResultBean getBusinessId(Integer id) {
		if(id==null || id==0) {
			return ResultBean.ERROR("请求参数为空");
		}
		List<Food> foodList=foodMapper.getBusinessId(id);
		return ResultBean.SUCCESS(foodList);
	}
}
